<template>
  <view class="medicine-dialogs" @touchmove.stop.prevent="">
    <!-- 库存管理弹框 -->
    <uv-popup ref="stockPopup" mode="center" round="10px">
      <view class="stock-dialog">
        <view class="dialog-content">
          <view class="medicine-info">
            <view class="medicine-tag">
              <text class="tag"
                :class="{'success': Number(medicineInfo.inventory) - Number(medicineInfo.threshold) > 0 &&medicineInfo.medicineName, 'warning': Number(medicineInfo.inventory) - Number(medicineInfo.threshold) <= 0&&medicineInfo.medicineName, 'danger': Number(medicineInfo.inventory) == 0&&medicineInfo.medicineName,'grey':!medicineInfo.medicineName}">{{
                medicineInfo.slotName || '-' }}</text>
              <text
                :class="{'success1': Number(medicineInfo.inventory) - Number(medicineInfo.threshold) > 0 &&medicineInfo.medicineName, 'warning2': Number(medicineInfo.inventory) - Number(medicineInfo.threshold) <= 0&&medicineInfo.medicineName, 'danger3': Number(medicineInfo.inventory) == 0&&medicineInfo.medicineName,'grey':!medicineInfo.medicineName}">库存数量
                {{ medicineInfo.inventory || 0 }}</text>
            </view>
            <view class="medicine-name">{{ medicineInfo.medicineName || '-' }}</view>
            <view class="medicine-detail">
              <text>69码：{{ medicineInfo.barCode || '-' }} | </text>
              <text class="blue-text" @click="copyCode(medicineInfo.barCode)">复制</text>
            </view>
            <view class="medicine-detail">生产厂家：{{ medicineInfo.manufacturer || '-' }}</view>
            <view class="medicine-detail">药品规格：{{ medicineInfo.medicineSpecifications || '-' }}</view>
            <view class="medicine-detail">剂型：{{ medicineInfo.dosageFormName || '-' }}</view>
          </view>
          <view class="dialog-btn" @click="openSupplyDialog">补药</view>
        </view>
      </view>
    </uv-popup>

    <!-- 补药弹框 -->
    <uv-popup ref="supplyPopup" mode="center" round="10px">
      <view class="supply-dialog">
        <view class="dialog-header">
          <text class="tag"
            :class="{'success': Number(medicineInfo.inventory) - Number(medicineInfo.threshold) > 0 &&medicineInfo.medicineName, 'warning': Number(medicineInfo.inventory) - Number(medicineInfo.threshold) <= 0&&medicineInfo.medicineName, 'danger': Number(medicineInfo.inventory) == 0&&medicineInfo.medicineName,'grey':!medicineInfo.medicineName}">{{
            medicineInfo.slotName }}</text>
          <text class="stock"
            :class="{'success1': Number(medicineInfo.inventory) - Number(medicineInfo.threshold) > 0 &&medicineInfo.medicineName, 'warning2': Number(medicineInfo.inventory) - Number(medicineInfo.threshold) <= 0&&medicineInfo.medicineName, 'danger3': Number(medicineInfo.inventory) == 0&&medicineInfo.medicineName,'grey':!medicineInfo.medicineName}">库存数量
            {{ medicineInfo.inventory || 0 }}</text>
          <!-- <view class="close-btn" @click="closeSupplyDialog">
            <uv-icon name="close" size="20" />
          </view> -->
        </view>
        <view class="dialog-content">
          <view class="medicine-name">{{ medicineInfo.medicineName||'-' }}</view>
          <view class="medicine-search">
            <input type="text" v-model="sixCode" placeholder="请输入或扫描69码" class="search-input" required />
            <view class="scan-btn" @click="getCode(1)">
              <image src="/static/index/scode.png" mode="widthFix" class="scan-icon" />
            </view>
            <view class="confirm-btn" @click="handleConfirm">确认</view>
          </view>
          <view class="medicine-box">
            <view class="medicine-detail">69码：{{ medicineInfo.barCode || '-' }}</view>
            <view class="medicine-detail">生产厂家：{{ medicineInfo.manufacturer || '-' }}</view>
            <view class="medicine-detail">药品规格：{{ medicineInfo.medicineSpecifications || '-' }}</view>
            <view class="medicine-detail">剂型：{{ medicineInfo.dosageFormName || '-' }}</view>
          </view>

          <view class="input-section">
            <view class="input-box">
              <input type="number" v-model="supplyAmount" placeholder="补药数量" @blur="handleAmountInput" />
            </view>
            <view class="input-right">
              <uv-switch v-model="isAddMedicine" @change="changeAddMedicine" />
            </view>
          </view>
          <view class="medicine-search" v-if="isAddMedicine">
            <input type="text" v-model="searchCode" placeholder="请输入或扫描追溯码" class="search-input" required />
            <view class="scan-btn" @click="getCode(2)">
              <image src="/static/index/scode.png" mode="widthFix" class="scan-icon" />
            </view>
            <view class="confirm-btn" @click="handleAdd" v-if="codeList.length < supplyAmount || !supplyAmount">添加
            </view>
          </view>
          <view class="code-section" v-if="isAddMedicine">
            <scroll-view class="scroll-view" :scroll-y="true">
              <view class="code-item" v-for="(item, index) in codeList" :key="index">
                <text>{{ item }}</text>
                <text class="blue-text" @click="deleteCode(index)">删除</text>
              </view>
            </scroll-view>
            <!-- <text class="blue-text" v-if="codeList.length < supplyAmount || !supplyAmount"
              @click="generateCode">生成追溯码</text> -->
          </view>

          <view class="dialog-footer">
            <view class="cancel-btn" @click="closeSupplyDialog">返回</view>
            <view class="confirm-btn" @click="handleSupply">补药</view>
          </view>
        </view>
      </view>
    </uv-popup>
    <uv-modal ref="modal" title="提示" content='关闭此模块可能存在监管风险，相关责任由店铺承担！' @confirm="confirmModal" @cancel="cancelModal"
      showCancelButton></uv-modal>
  </view>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { defineProps, defineEmits } from 'vue'
  import { generateTraceCode } from '@/api/storeManage'

  const props = defineProps({
    // 列表数据
    medicineInfo: {
      type: Object,
      default: () => { }
    }
  })
  const isAddMedicine = ref(true)
  const modal = ref(null)
  const codeList = ref([])
  // 弹框引用
  const stockPopup = ref(null)
  const supplyPopup = ref(null)
  const emit = defineEmits(['getSupply'])
  // 补药数量
  const supplyAmount = ref('')

  // 验证输入数量
  const validateAmount = (value) => {
    // 确保是正整数且大于0
    if (value == '' || parseInt(value) <= 0) {
      return ''
    }
    // 如果输入的是浮点数，只取整数部分
    return parseInt(value).toString()
  }

  // 监听输入变化
  const handleAmountInput = (e) => {
    supplyAmount.value = validateAmount(e.detail.value)
  }

  // 打开库存管理弹框
  const openStockDialog = () => {
    isAddMedicine.value = true
    stockPopup.value.open()
  }

  // 关闭库存管理弹框
  const closeStockDialog = () => {
    stockPopup.value.close()
  }

  const generateCode = () => {
    if (!supplyAmount.value) {
      uni.showToast({
        title: '请先输入补药数量',
        icon: 'none'
      })
      return
    }
    generateTraceCode().then(res => {
      if (res.code === 200) {
        codeList.value.push(res.data)
      }
    })
  }
  const handleAdd = () => {
    if (!supplyAmount.value) {
      uni.showToast({
        title: '请先输入补药数量',
        icon: 'none'
      })
      return
    }
    if (!searchCode.value && isAddMedicine.value) {
      uni.showToast({
        title: '追溯码不能为空',
        icon: 'none'
      })
      return
    }
    codeList.value.push(searchCode.value)
  }
  // 复制6号码
  const copyCode = (item) => {
    uni.setClipboardData({
      data: item
    })
    uni.showToast({
      title: '69码已复制',
      icon: 'success'
    })
  }

  const copyTraceCode = () => {
    uni.setClipboardData({
      data: medicineInfo.traceCode
    })
    uni.showToast({
      title: '追溯码已复制',
      icon: 'success'
    })
  }
  // 打开补药弹框
  const openSupplyDialog = () => {
    clearInfo()
    supplyPopup.value.open()
  }
  const clearInfo = () => {
    sixCode.value = ""
    supplyAmount.value = ''
    searchCode.value = ''
    codeList.value = []
  }
  const deleteCode = (index) => {
    codeList.value.splice(index, 1)
  }
  // 关闭补药弹框
  const closeSupplyDialog = () => {
    supplyPopup.value.close()
  }
  const changeAddMedicine = () => {
    if (!isAddMedicine.value) {
      modal.value.open()
    }
  }
  const confirmModal = () => {
    isAddMedicine.value = false
    modal.value.close()
  }
  const cancelModal = () => {
    isAddMedicine.value = true
    modal.value.close()
  }
  const getCode = (type) => {
    uni.scanCode({
      scanType: ['barCode', 'qrCode'],
      success: (res) => {
        // 扫码成功，将结果赋值给对应的输入框
        if (type == 1) {
          sixCode.value = res.result
        } else {
          searchCode.value = res.result
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '扫码失败，请重试',
          icon: 'none'
        })
      }
    })
  }
  // 处理补药
  const handleSupply = async () => {
    try {
      // 先执行 handleConfirm
      await handleConfirm()

      if (!supplyAmount.value || parseInt(supplyAmount.value) <= 0) {
        uni.showToast({
          title: '请输入正确的补药数量',
          icon: 'none'
        })
        return
      }
      if (codeList.value.length < supplyAmount.value && isAddMedicine.value) {
        uni.showToast({
          title: '请添加追溯码',
          icon: 'none'
        })
        return
      }
      if (codeList.value.length > supplyAmount.value && isAddMedicine.value) {
        uni.showToast({
          title: '补药数量应等于追溯码数量',
          icon: 'none'
        })
        return
      }
      const data = {
        inventory: supplyAmount.value,
        slotId: props.medicineInfo.slotId,
        traceabilityCodeList: codeList.value
      }
      // 等待 getSupply 事件执行完成
      await new Promise((resolve) => {
        emit('getSupply', data, resolve)
      })
      // 关闭弹框
      closeSupplyDialog()
      closeStockDialog()
    } catch (error) {
      console.log('handleConfirm 执行失败')
    }
  }

  const searchCode = ref('')
  const sixCode = ref('')

  const handleConfirm = () => {
    return new Promise((resolve, reject) => {
      if (!sixCode.value) {
        uni.showToast({
          title: '请输入69码',
          icon: 'none'
        })
        reject()
        return
      }
      if (sixCode.value != props.medicineInfo.barCode) {
        uni.showToast({
          title: '69码不匹配',
          icon: 'none'
        })
        reject()
        return
      } else {
        uni.showToast({
          title: '该69码正确',
          icon: 'none'
        })
        resolve()
      }
    })
  }


  // 暴露方法给父组件
  defineExpose({
    openStockDialog,
    openSupplyDialog,
    closeStockDialog,
    closeSupplyDialog
  })
</script>

<style lang="scss" scoped>
  .medicine-dialogs {

    .stock-dialog,
    .supply-dialog {
      background-color: #fff;
      border-radius: 12rpx;
      width: 650rpx;

      .dialog-header {
        position: relative;
        padding: 30rpx;
        text-align: center;
        margin-bottom: 0 !important;
        padding-bottom: 0 !important;

        .stock {
          margin-left: 20rpx;
          color: #00aa00;
        }

        .close-btn {
          position: absolute;
          right: 20rpx;
          top: 50%;
          transform: translateY(-50%);
        }
      }

      .medicine-tag,
      .dialog-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20rpx;

        .tag {
          background-color: #16A34A;
          color: #fff;
          padding: 7rpx 16rpx;
          font-size: 25rpx;
          border-radius: 30rpx;
        }

        .success {
          background: #07c160;
        }

        .warning {
          background: #ff9900;
        }

        .danger {
          background: #ff4d4f;
        }

        .success1 {
          color: #07c160;
        }

        .warning2 {
          color: #ff9900;
        }

        .danger3 {
          color: #ff4d4f;
        }
      }

      .dialog-content {
        padding: 30rpx 40rpx;
        font-size: 25rpx;

        .medicine-info {
          margin-bottom: 30rpx;
        }

        .medicine-name {
          font-size: 32rpx;
          font-weight: bold;
          border-bottom: 1px solid #eee;
          padding-bottom: 16rpx;
        }

        .medicine-detail {
          color: #666;
          margin-bottom: 18rpx;
          margin-top: 18rpx;
          font-size: 28rpx;

          .blue-text {
            color: #2979ff;
          }
        }

        .input-section {
          margin: 30rpx 0;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .input-box {
            width: 180rpx;
            border-radius: 30rpx;
            margin-top: 10rpx;
            border: 1px solid #eee;
            padding: 8rpx 30rpx;
            background: #eee;
            font-size: 23rpx;

            input {
              width: 100%;
            }
          }
        }

        .input-right {
          background: #fff;
        }

        .scroll-view {
          max-height: 200rpx;
          overflow-y: scroll;
        }

        .code-section {
          height: 200rpx;
          margin: 30rpx 0;
          color: #666;
          background: #f7f7f7;
          padding: 20rpx 26rpx 10rpx 26rpx;
          border-radius: 20rpx;
          margin-top: 20rpx;
          font-size: 25rpx;
          overflow-y: auto;
          -webkit-overflow-scrolling: touch;
          overscroll-behavior: contain;
          touch-action: pan-y;

          .code-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 2rpx 0;
          }

          text {
            display: block;
            margin-bottom: 10rpx;
          }

          .blue-text {
            color: #2979ff;
          }
        }

        .medicine-box {
          background: #f7f7f7;
          padding: 10rpx 26rpx;
          border-radius: 20rpx;
          margin-top: 20rpx;
          font-size: 25rpx;
        }

        .medicine-search {
          flex: 1;
          height: 70rpx;
          background: #f7f7f7;
          border-radius: 32rpx;
          display: flex;
          align-items: center;
          padding: 0 6rpx 0 24rpx;
          margin-top: 30rpx;
          margin-bottom: 10rpx;

          .search-input {
            flex: 1;
            height: 70rpx;
            background-color: #F5F5F5;
            border-radius: 8rpx;
            padding: 0 0 0 10rpx;
            font-size: 28rpx;
          }

          .scan-btn {
            width: 66rpx;
            height: 70rpx;
            background-color: #F5F5F5;
            display: flex;
            align-items: center;
            justify-content: center;

            .scan-icon {
              width: 40rpx;
              height: 40rpx;
            }
          }

          .confirm-btn {
            width: 100rpx;
            height: 62rpx;
            background-color: #fff;
            color: #9CA3AF;
            border-top-right-radius: 42rpx;
            border-bottom-right-radius: 42rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28rpx;
          }
        }
      }

      .dialog-btn {
        background-color: #2979ff;
        color: #fff;
        text-align: center;
        padding: 20rpx 0;
        border-radius: 50rpx;
      }

      .dialog-footer {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;

        .cancel-btn,
        .confirm-btn {
          width: 45%;
          text-align: center;
          padding: 14rpx 0;
          border-radius: 30rpx;
          font-size: 25rpx;
        }

        .cancel-btn {
          background-color: #f5f5f5;
          color: #9CA3AF;
        }

        .confirm-btn {
          background-color: #2979ff;
          color: #fff;
        }
      }
    }
  }
</style>